package ArrayList;

import java.util.Arrays;

public class SeqList {
    private Integer[] array;
    private int usedsize;
    private static final int DEFAULT_CAPACITY = 10;
    public SeqList() {
        this.array = new Integer[DEFAULT_CAPACITY];
    }
    public void display(){
        for (int i = 0; i < this.usedsize; i++) {
            System.out.print(this.array[i] + " ");
        }
        System.out.println();
    }
    private boolean isFull(){
        return this.usedsize == this.array.length;
    }
    public void add(int value) {
        if (this.isFull()) {
            this.array=Arrays.copyOf(this.array, this.array.length * 2);
            //扩容返回的是一个新数组的引用，需要接收
        }
        this.array[this.usedsize] = value;
        this.usedsize++;
    }
    public boolean contains(int value){
        for (int i = 0; i < this.usedsize; i++) {
            if(this.array[i] == value){
                return true;
            }
        }
        return false;
    }
    public int indexOf(int value) {
        for (int i = 0; i < this.usedsize; i++) {
            if(this.array[i] == value){
                return i;
            }
        }
        return -1;
    }
    private boolean checkPos(int pos) {
        if (pos < 0 || pos >= this.usedsize) {
            return false;
        }
        return true;
    }
    public int get(int pos){
        if(this.checkPos(pos)){
            throw new IndexOutOfBoundsException();
        }
        return this.array[pos];
    }
    public void add(int pos, int value) {
        if(this.isFull()){
            this.array=Arrays.copyOf(this.array, this.array.length * 2);
        }
        if(pos < 0 || pos > this.usedsize){
            throw new IndexOutOfBoundsException();
        }
        for(int i = usedsize-1; i >= pos; i--){
            array[i+1]=array[i];
        }
        array[pos]=value;
        usedsize++;
    }
    public void set(int pos, int value) {
        if(this.checkPos(pos)){
            this.array[pos] = value;
        }
    }
    public int size(){
        return this.usedsize;
    }
    //删除第一次出现的value值
    public void remove(int value) {
        if(usedsize == 0){
            System.out.println("当前顺序表有效长度为0");
            return;
        }
        int index = this.indexOf(value);
        if (index == -1) {
            System.out.println("不存在需要删除的value值："+value);
            return;
        }
        for(int i =index;i<usedsize-1;i++){
            this.array[i]=this.array[i+1];
        }
        usedsize--;
        //如果数组中的元素是引用类型，需要置空来回收，
        //需要 array[usedsize-1] = null;
    }
    public void clear(){
        //如果数组中的元素是引用类型，需要置空来回收，
        //for 循环全部置空
        usedsize = 0;
    }
}
